<?php

class TestDbLinkTool  extends UnitTestCase {

    var $cfg = array(
        'db' => 'unit_tests');

    function testFactory() {
        $cfg = array(
            'dblink'=>array(
                'host' => 'localhost'
                ,'user' => 'root'
                ,'db' => 'home'));
        $link = DbLinkTool::toolFactory('webappkit.db',$cfg);
        $this->assertIsA($link, 'DbLinkTool'
            , "::toolFactory(kit_id, cfg) should return a DbLinkTool object");
        // checking cfg override
        $full_cfg = array(
            'dblink' => array(
                'host'=>'localhost'
                , 'db' => 'home'
                , 'user' => 'root'
                , 'pwd' => null
                , 'encoding' => null));
        if (!$this->assertEqual($link->getCfg(), $full_cfg
            , 'config should be properly overriden')) {
            $this->dump($link->getCfg());
        }
    }

    function testConnexionDefaults() {
        // testing connexion without custom cfg
        // getting tool
        $link = DbLinkTool::toolFactory('webappkit.db',array());
        $this->assertTrue($link->connect()
            , 'connect() should return true using stored config (localhost, root, no password)');

        // selecting a database
        $db = $this->cfg['db'];
        $bad_db = 'i_do_not_exist';
        $this->assertFalse($link->selectDb($bad_db)
            , "selectDb($bad_db) shall return false when failing to select a db");


        $this->assertTrue($link->selectDb($db)
            , "selectDb($db) should return true when selecting a db");

        if (!$this->assertEqual($link->getDb(), $db
            , "getDb($db) should then return the selected db name ($db)")) {
            $this->dump($link);
        }

        $encoding = 'utf8';
        $this->assertTrue($link->setEncoding($encoding)
            ,"setEncoding($encoding) should return true");

        if (!$this->assertEqual($link->getEncoding(), $encoding
            ,"...and set the encoding.")) {
            $this->dump($link->getEncoding());
        }
    }

    function testConnexionFullCfg() {
        $cfg = array(
            'dblink'=>array(
                'db' => 'unit_tests'
                ,'encoding' => 'utf8'));

        $link = DbLinkTool::toolFactory('webappkit.db',$cfg);

        $this->assertTrue($link->connect()
            , 'connect() should return true...');

        if (!$this->assertEqual($link->getDb(), 'unit_tests'
            , "... having selected the database...")) {
            $this->dump($link);
        }

        if (!$this->assertEqual($link->getEncoding(), 'utf8'
            ,"...and set the encoding.")) {
            $this->dump($link->getEncoding());
        }
    }

}